package com.yuanfeng.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.business.entity.ShopClassBindEntity;
import com.yuanfeng.business.entity.ShopClassBindTmpEntity;
import com.yuanfeng.business.mapper.ShopClassBindMapper;
import com.yuanfeng.business.mapper.ShopClassBindTmpMapper;
import com.yuanfeng.business.service.ShopClassBindTmpService;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.StringUtils;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.goods.GdbMerchantGoodsCatVO;
import com.yuanfeng.commoms.vo.shop.ApplyCatVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 */
@Service
public class ShopClassBindTmpServiceImpl extends ServiceImpl<ShopClassBindTmpMapper, ShopClassBindTmpEntity>
    implements ShopClassBindTmpService{

    @Autowired
    private ShopClassBindMapper shopClassBindMapper;
    @Override
    public ResponseResult queryShopCat(Map<String, Object> map) {

        IPage<ApplyCatVO> page=this.baseMapper.queryShopCat(new Query<ApplyCatVO>().getPage(map),
                map);
        if (page.getRecords() != null && page.getRecords().size() > 0){
            for (ApplyCatVO applyCatEntity : page.getRecords()) {
                //查询类目
                List<ApplyCatVO> list = this.baseMapper.queryShopCatDetail(applyCatEntity.getBatchId(), null);
                applyCatEntity.setCatTotal(list.size());
            }
        }

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryShopCatDetail(Map<String, Object> map) {


        //查询类目
        IPage<ApplyCatVO> page=this.baseMapper.queryShopCatDetailByPage(new Query<ApplyCatVO>().getPage(map),
                map);
        if (page.getRecords() != null && page.getRecords().size() > 0){
            for (ApplyCatVO applyCatEntity : page.getRecords()) {
                String catName = applyCatEntity.getCatName();
                List<String> strings = JSON.parseArray(catName, String.class);
                applyCatEntity.setCatNames(strings);
            }
        }
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult process(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER + token);
        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

        String batchId = String.valueOf(map.get("batchId"));
        Integer state = (Integer) map.get("state");
        if (state == 2) {
            //审核通过
            //查询类目
            ShopClassBindEntity param = new ShopClassBindEntity();
            List<ApplyCatVO> queryshopcat = this.baseMapper.queryShopCatDetail(String.valueOf(map.get("batchId")), null);
            for (ApplyCatVO applyCatEntity : queryshopcat) {

                param.setProductClassId(applyCatEntity.getCatId());
                param.setShopId(applyCatEntity.getShopId());

                param.setShopClassBindEnable(1);
                param.setShopClassBindId(null);
                param.setBabyCommission(new BigDecimal("0"));
                //查询当前分类
                GdbMerchantGoodsCatVO goodsCat = this.baseMapper.selectGoodsCatByPrimaryKey(param.getProductClassId());

                param.setProductCatIds(goodsCat.getCatId().toString());
                param.setCommissionRate(new BigDecimal(goodsCat.getCatCommission()));
                //添加或修改经营类目
                shopClassBindMapper.insert(param);
            }
        }
        //更新状态
        Integer integer = this.baseMapper.update(null,new LambdaUpdateWrapper<ShopClassBindTmpEntity>()
                          .eq(ShopClassBindTmpEntity::getBatchId,batchId)
                          .set(ShopClassBindTmpEntity::getStart,state)
                          .set(ShopClassBindTmpEntity::getReason,String.valueOf(map.get("reason"))));
        if (integer > 0) {
            return ResponseResult.success("审核成功");
        }

        return ResponseResult.fail(0, "审核失败");
    }

    @Override
    public ResponseResult qureyApplycat(Map<String, Object> map) {
        String token = (String) map.get("token");
        if(token!=null) {
            UserInfoVO userInfo =ParseTokenUtils.getUserInfoByToken(token);
            if(userInfo==null){
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
            }
            String shopId = userInfo.getShopId();

            IPage<ShopClassBindTmpEntity> page=this.page(new Query<ShopClassBindTmpEntity>().getPage(map),
                                                new LambdaQueryWrapper<ShopClassBindTmpEntity>()
                                                .eq(ShopClassBindTmpEntity::getShopId, shopId)
                                                .like(map.containsKey("catName"),ShopClassBindTmpEntity::getCatName,map.containsKey("catName")?map.get("catName").toString():null));

            if (!CollectionUtils.isEmpty(page.getRecords())){
                for (ShopClassBindTmpEntity applyCatEntity : page.getRecords()) {
                    map.put("batchId",applyCatEntity.getBatchId());
                    List<ApplyCatVO> querycat = this.baseMapper.querycat(map);
                    if (!CollectionUtils.isEmpty(querycat)){
                        for (ApplyCatVO catEntity : querycat) {
                            String catName = catEntity.getCatName();
                            List<String> strings = JSON.parseArray(catName, String.class);
                            catEntity.setCatNames(strings);
                        }
                    }

                    applyCatEntity.setCatEntities(querycat);
                }
            }
            return ResponseResult.success(PageUtils.getPage(page));
        }else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_NULL);
        }
    }

    @Override
    public ResponseResult applyCat(Map<String, Object> map) {
        String token = (String) map.get("token");
        if(token!=null) {
            UserInfoVO userInfo =ParseTokenUtils.getUserInfoByToken(token);
            if(userInfo==null){
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
            }
            String shopId = userInfo.getShopId();
            String batchId = String.valueOf(map.get("batchId"));
            if (StringUtils.isEmpty(batchId)) {
                //生成批次id
                StringBuffer id = new StringBuffer();
                DateFormat dFormat3 = new SimpleDateFormat("yyyyMMdd");

                String format = dFormat3.format(new Date());

                Random random = new Random();
                String verificationCode = String.valueOf(random.nextInt(9) + 1);
                for (int i = 0; i < 5; i++) {
                    verificationCode += random.nextInt(10);
                }
                id.append(format).append(verificationCode);
                map.put("batchId",id.toString());
            }
            Integer integer = 0;

            map.put("shopId",shopId);
            map.put("start",1);
            List<Integer> catId = (List) map.get("catId");
            ArrayList<Object> list = new ArrayList<>();
            for (Integer o : catId) {
                HashMap<Object, Object> hashMap = new HashMap<>();
                List<String> querycatname = this.baseMapper.queryCatName(o);
                String s = JSON.toJSONString(querycatname);

                hashMap.put("catId",o);
                hashMap.put("catName",s);

                list.add(hashMap);
            }
            map.put("catId",list);
            if (StringUtils.isEmpty(batchId)) {
                //新增
                integer = this.baseMapper.insertClassBind(map);
            }else{
                //修改
                this.baseMapper.delete(new LambdaQueryWrapper<ShopClassBindTmpEntity>()
                                .eq(ShopClassBindTmpEntity::getShopId,map.get("shopId").toString())
                                .eq(ShopClassBindTmpEntity::getBatchId,map.get("batchId").toString()));

                integer = this.baseMapper.insertClassBind(map);
            }

            if (integer > 0){
                return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
            }
            return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);


        }else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_NULL);
        }
    }

    @Override
    public ResponseResult deleteClassBindTmp(Integer catId) {
        this.baseMapper.delete(new LambdaQueryWrapper<ShopClassBindTmpEntity>()
                .eq(ShopClassBindTmpEntity::getCatId,catId));
        return ResponseResult.success();
    }

}




